<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="三方平台设置" width="100%" @ok="handleSubmit" showFooter>
    <!--    <div>
          <a-row class="  p-2 my-1" v-for="item in useTagAreaList" :key="item.tagAreaConfigId">
            <a-col :span="6" ><a-checkbox v-model:checked="item.tagChecked" ><a-typography-title :level="5">{{item.name}}</a-typography-title></a-checkbox>   </a-col>
            <a-col :span="18">
              <a-tree-select
                v-model:value="item.userCityList"
                style="width: 100%"
                :tree-data="provinceAndCityData"
                tree-checkable
                allow-clear
                :show-checked-strategy="TreeSelect.SHOW_CHILD"
                placeholder="请选择城市"
                tree-node-filter-prop="label"
                allowClear


              />
            </a-col>
          </a-row>
        </div>-->
    <a-table
      :loading="useTpCarDsLoading"
      size="middle"
      :row-selection="rowSelection"
      rowKey="tpCarConfigId"
      :dataSource="useTpCarDs"
      :columns="columns"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'configStatus'">
          <a-switch v-model:checked="record.configStatus" checkedValue="Y" unCheckedValue="N" />
        </template>
        <template v-if="column.dataIndex === 'izFilter'">
          <a-switch v-model:checked="record.izFilter" checkedValue="Y" unCheckedValue="N" />
        </template>
        <template v-if="column.dataIndex === 'delayPushTime'">
          <a-input-number v-model:value="record.delayPushTime" />
        </template>
        <template v-if="column.dataIndex === 'tpUsername'">
          <a-input v-model:value="record.tpUsername" placeholder="平台用户名" />
        </template>
        <template v-if="column.dataIndex === 'tpPassword'">
          <a-input v-model:value="record.tpPassword" placeholder="平台密码" />
        </template>
        <template v-if="column.dataIndex === 'tpSecretKey'">
          <a-input v-model:value="record.tpSecretKey" placeholder="平台秘钥" />
        </template>
        <template v-if="column.dataIndex === 'userCityList'">
          <!--          <a-tree-select
                      v-model:value="record.userCityList"
                      style="width: 100%"
                      :tree-data="provinceAndCityData"
                      tree-checkable
                      allow-clear
                      :show-checked-strategy="TreeSelect.SHOW_CHILD"
                      placeholder="请选择城市"
                      tree-node-filter-prop="label"
                      allowClear
                    />-->
          <a-textarea v-model:value="record.userCityList" placeholder="请输入城市,多个城市用,隔开" />
        </template>
      </template>
    </a-table>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { reactive, ref } from 'vue';
  import { TreeSelect } from 'ant-design-vue';
  import { provinceAndCityData } from '@/components/Form/src/utils/areaDataUtil';
  import { cloneDeep } from 'lodash-es';
  import { clueUserTpCarBatchSet, userTpCarList } from '@/views/clue/tpCarConfig/ClueTpCarConfig.api';

  const emit = defineEmits(['success', 'register']);

  const rowSelection = reactive({
    onChange: (selectedRowKeys, selectedRows) => (rowSelection.selectedRowKeys = selectedRowKeys),
    selectedRowKeys: [],
  });

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      align: 'center',
      customRender: ({ text, record, index }) => `${index + 1}`,
      width: '2%',
    },
    {
      title: '平台名称',
      dataIndex: 'name',
      width: '8%',
    },
    {
      title: '推送状态',
      dataIndex: 'configStatus',
      width: '8%',
    },
    {
      title: '筛选状态',
      dataIndex: 'izFilter',
      width: '8%',
    },

    {
      title: '推送延迟(秒)',
      dataIndex: 'delayPushTime',
      width: '10%',
    },
    {
      title: '平台用户名',
      dataIndex: 'tpUsername',
      width: '10%',
    },
    {
      title: '平台密码',
      dataIndex: 'tpPassword',
      width: '10%',
    },
    {
      title: '平台秘钥',
      dataIndex: 'tpSecretKey',
      width: '10%',
    },
    {
      title: '城市',
      dataIndex: 'userCityList',
      width: '50%',
    },
  ];

  /**
   * 获取配置项
   */
  const useTpCarDs = reactive([]);
  const useTpCarDsLoading = ref(false);
  const getUserTpCar = (userId) => {
    useTpCarDs.splice(0, useTpCarDs.length);
    useTpCarDsLoading.value = true;
    userTpCarList({ userId })
      .then((res) => {
        const userTpCarConfigList = res.map((item) => {
          // item.userCityList = item.userCityList ? item.userCityList.split(',') : [];
          return item;
        });
        useTpCarDs.splice(0, useTpCarDs.length, ...userTpCarConfigList);

        rowSelection.selectedRowKeys.splice(
          0,
          rowSelection.selectedRowKeys.length,
          ...res.filter((item) => item.tpCarConfigId == item.tpCarId).map((item) => item.tpCarId)
        );
      })
      .finally(() => {
        useTpCarDsLoading.value = false;
      });
  };

  const optUser = ref({});
  // open
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    optUser.value = data.user;

    getUserTpCar(data.user.id);
  });

  // 确定
  const handleSubmit = async () => {
    try {
      setDrawerProps({ confirmLoading: true });
      //  提交表单
      let formList = cloneDeep(useTpCarDs);
      formList = formList.map((item) => {
        item.userId = optUser.value.id;
        // item.userCityList = item.userCityList.join(',')
        if (rowSelection.selectedRowKeys.includes(item.tpCarConfigId)) {
          item.tpCarId = item.tpCarConfigId;
        } else {
          item.tpCarId = '';
        }
        return item;
      });
      await clueUserTpCarBatchSet(formList);
      // 关闭弹窗
      closeDrawer();
      // 刷新列表
      emit('success', {});
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  };
</script>
